const getMysql = require('../mysql')

const register = (req, res) => {
    let unames = req.body.uname
    let pass = req.body.password
    let iphones = req.body.iphone
    console.log(unames,pass,iphones);
    // 注册前查询
    let sql = "select uname from tarvel_user where uname=?"
    let sql2 = "select iphone from tarvel_user where iphone=?"
    getMysql(sql,unames).then(result=>{
        console.log(result);
        if(result.length !== 0){
            res.send({
                code: 201,
                message: '该用户名已经注册过！'
            })
        }else{
            getMysql(sql2,iphones).then(result2=>{
                console.log(result2);
                if(result2.length !== 0){
                    res.send({
                        code: 203,
                        message: '该手机号已经注册过！'
                    })
                }else{
                    getCatuser()
                }
            })
        }
        
    }).catch(err=>{
        console.log(err);
    })

    // 写入数据库
    function getCatuser() {
        let sql3 = 'insert into tarvel_user(uname,password,iphone) values (?,password(?),?)'
        getMysql(sql3, unames, pass, iphones).then(result => {
            res.send({
                code: 200,
                message: '注册成功'
            })
        }).catch(err => {
            console.log(err);
            res.send({
                code: 202,
                message: '注册失败'
            })
        })
    }

}
module.exports = { register }